package com.ruoyi.business.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


import java.util.Date;

import com.ruoyi.business.domain.DispatchLists;
import com.ruoyi.business.service.IDispatchListsService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import org.apache.commons.lang3.StringUtils;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.business.dao.DispatchListDao;
import com.ruoyi.business.domain.DispatchList;
import com.ruoyi.business.service.IDispatchListService;
import com.ruoyi.framework.web.service.TokenService;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * DispatchListService业务层处理
 *
 * @author liutietou
 * @since 1.0 2025-07-19
 */
@Transactional(readOnly = true)
@Service
public class DispatchListServiceImpl implements IDispatchListService {

    @Autowired
    private DispatchListDao dispatchListDao;
    @Autowired
    private IDispatchListsService  dispatchListsService;
    @Autowired
    TokenService tokenService;
    /**
     * 查询DispatchList
     *
     * @param dlid DispatchListID
     * @return DispatchList
     */
    @Override
    public DispatchList findById(Integer dlid) {
        return dispatchListDao.findById(dlid).get();
    }

    /**
     * 分页查询DispatchList列表
     *
     * @param req DispatchList
     * @return DispatchList
     */
    @Override
    public Page<DispatchList> findDispatchListPage(DispatchList req) {
        Specification<DispatchList> example = formatQueryParams(req);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Pageable pageable = PageRequest.of(pageDomain.getPageNo(),
                Optional.ofNullable(pageDomain.getPageSize()).orElse(PageDomain.DEFAULT_PAGE_SIZE),
                Sort.Direction.DESC,
                Optional.ofNullable(pageDomain.getOrderByColumn()).orElse("dlid"));
        Page<DispatchList> page = dispatchListDao.findAll(example, pageable);
        return page;
    }

    /**
     * 分页查询DispatchList列表
     *
     * @param req DispatchList
     * @return DispatchList
     */
    @Override
    public List<DispatchList> findDispatchListList(DispatchList req) {
        Specification<DispatchList> example = formatQueryParams(req);
        List<DispatchList> list = dispatchListDao.findAll(example, Sort.by(Sort.Direction.DESC,"dlid"));
        return list;
    }

    private Specification<DispatchList> formatQueryParams(DispatchList req){
        Specification<DispatchList> example = new Specification<DispatchList>() {
            private static final long serialVersionUID = 1L;
            SysUser sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
            @Override
            public Predicate toPredicate(Root<DispatchList> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (null != req.getDlid()){
                    Predicate pre = cb.equal(root.get("dlid").as(Integer.class), req.getDlid());
                    list.add(pre);
                }
                if (StringUtils.isNotBlank(req.getCdlcode())){
                    Predicate pre = cb.equal(root.get("cdlcode").as(String.class), req.getCdlcode());
                    list.add(pre);
                }
                  //只显示网上订货系统的现销单
                    Predicate xxvouchPre = cb.equal(root.get("cstcode").as(String.class), "XX");
                    list.add(xxvouchPre);

                if (null != req.getDdateRange()){
                    Predicate pre1 = cb.greaterThanOrEqualTo(root.get("ddate").as(Date.class), req.getDdateRange().get(0));
                    Predicate pre2 = cb.lessThanOrEqualTo(root.get("ddate").as(Date.class), req.getDdateRange().get(1));
                    list.add(pre1);
                    list.add(pre2);
                }

                if(!sysUser.isAdmin() && null!=sysUser.getCust()){
                    Predicate pre = cb.equal(root.get("ccuscode").as(String.class), sysUser.getCust().getCcuscode());
                    list.add(pre);
                }

                if (StringUtils.isNotBlank(req.getCcuscode())){
                    Predicate pre = cb.equal(root.get("ccuscode").as(String.class), req.getCcuscode());
                    list.add(pre);
                }

                if (StringUtils.isNotBlank(req.getCshipaddress())){
                    Predicate pre = cb.like(root.get("cshipaddress").as(String.class),"%"+ req.getCshipaddress()+"%");
                    list.add(pre);
                }



                if (StringUtils.isNotBlank(req.getCmemo())){
                    Predicate pre = cb.equal(root.get("cmemo").as(String.class), req.getCmemo());
                    list.add(pre);
                }


                if (StringUtils.isNotBlank(req.getCverifier())){
                    Predicate pre = cb.equal(root.get("cverifier").as(String.class), req.getCverifier());
                    list.add(pre);
                }
                if (StringUtils.isNotBlank(req.getCmaker())){
                    Predicate pre = cb.equal(root.get("cmaker").as(String.class), req.getCmaker());
                    list.add(pre);
                }

                if (StringUtils.isNotBlank(req.getCcusname())){
                    Predicate pre = cb.like(root.get("ccusname").as(String.class), "%" + req.getCcusname()+ "%");
                    list.add(pre);
                }

                if (StringUtils.isNotBlank(req.getCdefine11())){
                    Predicate pre = cb.like(root.get("cdefine11").as(String.class),"%"+ req.getCdefine11()+"%");
                    list.add(pre);
                }





                if (list.isEmpty()) {
                    return null;
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        return example;
    }

    /**
     * 保存（新增/修改）DispatchList
     *
     * @param dispatchList DispatchList
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(DispatchList dispatchList) {
        if(dispatchList.getDlid()==null||dispatchList.getDlid()==0){
            dispatchList.setDlid(getAndUpdateId(("001")));
        }
        dispatchList.setCinvoicecompany(dispatchList.getCcuscode());
        dispatchListDao.save(dispatchList);
        List<DispatchLists>  list=dispatchList.getDispatchLists();
        for(DispatchLists  item:list){
            item.setDlid(dispatchList.getDlid());
            item.setCbsysbarcode("||SA01|"+dispatchList.getCdlcode()+"|"+item.getIrowno());
        }
        this.dispatchListsService.save(list,dispatchList.getDlid());
    }


    private  int  getAndUpdateId(String accountid){
        int  dlid=this.dispatchListDao.getDispatchId(accountid)+110*1000000;
        this.dispatchListDao.updateDispatchId(accountid);
        return  dlid;
    }
    /**
     * 批量删除DispatchList
     *
     * @param dlids 需要删除的DispatchListID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(List<Integer> dlids) {
        List<DispatchList> existBeans = dispatchListDao.findAllById(dlids);
        if(!existBeans.isEmpty()){
            dispatchListDao.deleteAll(existBeans);
        }
    }

    /**
     * 删除DispatchList信息
     *
     * @param dlid DispatchListID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDispatchListById(Integer dlid) {
         dispatchListDao.deleteById(dlid);
    }

@Override
    public  String   getCdlcode(){
        String  yearmonth= DateUtils.parseDateToStr("yyyyMM",new Date());
        String dlid=this.dispatchListDao.getCdlcode("XX"+yearmonth+"%");
        if(StringUtils.isBlank(dlid)){
            dlid="XX"+yearmonth+"0001";
        }else {
            String  suffix=dlid.substring(8);
            if(suffix.matches("\\d+")){
                dlid="XX"+yearmonth+String.valueOf(Integer.valueOf(suffix)+10001).substring(1);
            }else {
                dlid="XX"+yearmonth+"0001";
            }
        }
        return  dlid;
    }
}
